package com.zhangxin.threadcoreknowledge.threadobjectclasscommonmethods;

/**
 * 交替打印奇数和偶数,利用 synchronized实现
 */
public class Demo05WaitNotifyPrintOddEvenSyn {

    private static int count;

    private static final Object object = new Object();

    // 1.用2个线程,一个打奇数,一个打印偶数
    // 2.通过synchronized来对一个对象进行加锁,保证一个时间内,只能有一个线程拿到这个对象的锁,从而执行代码块中的内容

    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (count < 100) {
                    synchronized (object) {
                        if ((count & 1) == 0 ) {
                            System.out.println(Thread.currentThread().getName() + ":" + count++);
                        }
                    }
                }
            }
        }, "odd-Thread").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (count < 100) {
                    synchronized (object) {
                        if ((count & 1) == 1) {
                            System.out.println(Thread.currentThread().getName() + ":" + count++);
                        }
                    }
                }
            }
        }, "even-Thread").start();

    }
}
